package com.demo.mmap;

import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author cxx
 * @create 2020-04-08 15:35
 **/
public class TestMmap {

    public static void main(String[] args) {


        File file = new File ("ss.log");
        if (!file.exists ()) {
            try {
                file.createNewFile ();
            } catch (IOException e) {
                e.printStackTrace ();
            }
        }
        try (FileOutputStream stream = new FileOutputStream (file)) {

            for (int i = 0; i < 10; i++) {
                stream.write (String.valueOf (i).getBytes ());
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace ();
        } catch (IOException e) {
            e.printStackTrace ();
        }


    }

    private static void mmap() {
        RandomAccessFile file= null;
        FileChannel channel = null;
        try {
            file = new RandomAccessFile ("/mm.log", "rw");
            channel = file.getChannel ();
            MappedByteBuffer buffer = channel.map (FileChannel.MapMode.READ_WRITE, 0, 10);
            for (int i = 0; i < 10; i++) {
                buffer.put(String.valueOf (i).getBytes ());
            }
            channel.write (buffer);

        } catch (Exception e) {
            e.printStackTrace ();
        }finally {
            if(file != null) {
                try {
                    file.close ();
                } catch (IOException e) {
                }
            }
            if(channel != null){
                try {
                    channel.close ();
                } catch (IOException e) {
                }
            }
        }
    }

}
